﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Ipmce.RemoteVoting.Backend.DataAccess.Exceptions;

namespace Ipmce.RemoteVoting.Backend.DataAccess
{
	public class VoterRepository : IVoterRepository
	{
		private readonly RemoteVotingContext _context;

		public VoterRepository(RemoteVotingContext context)
		{
			_context = context;
		}

		public Voter GetById(long id)
		{
			var result = _context.Voters.Find(id);
			if (null == result)
			{
				throw new EntityNotFoundException("Voter not found");
			}
			return result;
		}

		public Voter GetByPassportNumber(string passportNumber)
		{
			return GetVoter(v => v.PassportNumber == passportNumber);
		}

		public Voter GetByThumbprint(string certificateSubjectKeyId)
		{
			return GetVoter(v => v.CertificateThumbPrint == certificateSubjectKeyId);
		}

		public void CommitChanges()
		{
			_context.SaveChanges();
		}

		public IList<Voter> GetAllVoters()
		{
			return _context.Voters.ToList();
		}

		private Voter GetVoter(Expression<Func<Voter, bool>> filter)
		{
			try
			{
				return _context.Voters.Single(filter);
			}
			catch (InvalidOperationException err)
			{
				throw new EntityNotFoundException("Voter not found", err);
			}
		}
	}
}